package com.b2c.erp.controller.douyin;

import com.b2c.entity.api.ApiResult;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.dou.DouyinOrderService;
import com.b2c.entity.vo.DyOrderImportOrderVo;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/douyin")
@RestController
public class DyOrderImportAjaxController {
    @Autowired
    private ErpGoodsService erpGoodsService;

    @Autowired
    private DouyinOrderService douyinOrderService;

    private static Logger log = LoggerFactory.getLogger(DyOrderImportAjaxController.class);

    /***
     * 从菜单打印订单导出excel中批量发货
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @RequestMapping(value = "/order_excel_import_review_ajax", method = RequestMethod.POST)
    public ApiResult<List<DyOrderImportOrderVo>> orderSendExcel(@RequestParam("excel") MultipartFile file, HttpServletRequest req) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
        System.out.println(destFileName);

        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********导入抖音订单，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");
        InputStream fis = null;
        fis = new FileInputStream(destFileName);
        if (fis == null) return new ApiResult<>(502, "没有文件");

        destFile.deleteOnExit();
        Workbook workbook = null;
        
        try {
            if (fileName.toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (fileName.toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(fis);
            }
            // workbook = new HSSFWorkbook(fis);
        } catch (Exception ex) {
            log.info("/***********导入抖音订单***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        if (workbook == null) return new ApiResult<>(502, "未读取到Excel文件");


        /****************开始处理批批网csv订单****************/
        //订单list
        List<DyOrderImportOrderVo> list = new ArrayList<>();
        Sheet sheet = null;

        try {
            sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();//最后一行索引
            Row row = null;
//            Map<String, PictureData>  maplist=null;
//            maplist = getPictures2((XSSFSheet) sheet);
            for (int i = 1; i <= lastRowNum; i++) {
                row = sheet.getRow(i);
                //订单数据
                String orderId = row.getCell(0).getStringCellValue().replace("\t", "");

                //查找订单号是否存在
                var orderTmp = list.stream().filter(p->p.getOrderId().trim().equals(orderId.trim())).findFirst();


                DyOrderImportOrderVo r = new DyOrderImportOrderVo();
                r.setOrderId(orderId);
                log.info("/***********导入抖音订单***读取到订单编号:" + orderId + "***********/");

                if (StringUtils.isEmpty(orderId) == false) {
                    //订单内容
                    String payTypeName = row.getCell(17).getStringCellValue();
                    r.setPayTypeName(payTypeName);
                    String province = row.getCell(21).getStringCellValue();
                    r.setProvince(province);
                    String city = row.getCell(22).getStringCellValue();
                    r.setCity(city);
                    String town = row.getCell(23).getStringCellValue();
                    r.setTown(town);
                    String street=row.getCell(24).getStringCellValue();
                    r.setStreet(street);
                    try {
                        String buyerWords = row.getCell(27).getStringCellValue();
                        r.setBuyerWords(buyerWords);
                        String sellerWords = row.getCell(30).getStringCellValue();
                        r.setSellerWords(sellerWords);
                    } catch (Exception e) {
                    }
                    
                    String orderCreateTime = row.getCell(28).getStringCellValue();
                    r.setOrderCreateTime(orderCreateTime);
                    try{
                        String orderPayTime = row.getCell(32).getStringCellValue();
                        r.setOrderPayTime(orderPayTime);
                    }catch(Exception e){
                        r.setOrderPayTime("");
                    }
                    String appSource = row.getCell(33).getStringCellValue();
                    r.setAppSource(appSource);
                    String trafficeSource = row.getCell(34).getStringCellValue();
                    r.setTrafficeSource(trafficeSource);
                    String orderStatusStr = row.getCell(35).getStringCellValue();
                    r.setOrderStatusStr(orderStatusStr);
                    String expShipTime = row.getCell(36).getStringCellValue();
                    r.setExpShipTime(expShipTime);
                    try {
                        String authorId =  row.getCell(39).getStringCellValue();
                        r.setAuthorId(authorId);
                        String authorName =  row.getCell(40).getStringCellValue();
                        r.setAuthorName(authorName);
                    }catch (Exception e) {
                    }

                    //订单商品信息
                    String subOrderId = row.getCell(1).getStringCellValue();
                    r.setSubOrderId(subOrderId);
                    String productName = row.getCell(2).getStringCellValue();
                    r.setProductName(productName);
                    String specDesc = row.getCell(3).getStringCellValue();
                    r.setSpecDesc(specDesc);
                    Double quantity = row.getCell(4).getNumericCellValue();
                    r.setQuantity(quantity);
                    String productId = row.getCell(5).getStringCellValue();
                    r.setProductId(productId);
                    String specCode= row.getCell(6).getStringCellValue();
                    r.setSpecCode(StringUtils.hasText(specCode)?specCode.trim():"");
                    Double price = row.getCell(7).getNumericCellValue();
                    r.setPrice(price);
                    Double totalAmount = row.getCell(8).getNumericCellValue();
                    r.setTotalAmount(totalAmount);
                    Double postAmount = row.getCell(9).getNumericCellValue();
                    r.setPostAmount(postAmount);
                    Double couponAmount = row.getCell(10).getNumericCellValue();
                    r.setCouponAmount(couponAmount);
                    
                    list.add(r);
                }


                


            }


        } catch (Exception ex) {
            log.info("/***********导入批批网订单***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        return new ApiResult<>(0, "SUCCESS", list);
    }



    /***
     * 导入订单
     * @param req
     * @return
     */
    @RequestMapping(value = "/order_excel_import_review_submit", method = RequestMethod.POST)
    public ApiResult<String> orderExcelImportSubmit(@RequestBody DyOrderImportSubmitReq req) {
//        if (req.getBuyerUserId() == null || req.getBuyerUserId() == 0)
//            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有buyerUserId");

        List<DyOrderImportOrderVo> orderList = req.getOrderList();
        if (orderList == null || orderList.size() == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有orderList");
        Integer shopId = req.getShopId();
        /*************excel订单货号检查，1是否填写了，2是否存在 ********** **************/
        // for (var order : orderList) {

        //         if (StringUtils.isEmpty(order.getSpecCode())) {
        //             return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：订单" + order.getOrderId() + "没有货号");
        //         } else {
        //             //查询商品信息
        //             var erpGoods = erpGoodsService.getSpecByNumber(order.getSpecCode());
        //             if (erpGoods == null) {
        //                 return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：订单" + order.getOrderId() + ",商品sku编码:" + order.getSpecCode() + "不存在");
        //             } 
        //         }
            
        // }

        ResultVo<String> resultVo = douyinOrderService.importExcelOrder(orderList,shopId);

        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS", resultVo.getData());
        } else return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
    }

}
